import request from 'umi-request';

export default {
  namespace: 'employeeList',

  state: [],

  reducers: {
    update(_, { payload }) {
      const { employeeList } = payload;
      return employeeList;
    },
    addEmployee(state, { payload }) {
      const { employee } = payload;
      state.push(employee);
      return state;
    },

    updateEmployee(state, { payload }) {
      const { employee: newEmployee } = payload;

      return {
        state: state.map((e) => (e.key === newEmployee.key ? newEmployee : e)),
      };
    },

    delete(state, { payload }) {
      const { key: targetKey } = payload;

      return state.filter((e) => e.key !== targetKey);
    },
  },

  effects: {
    *add({ employee }, { put }) {
      const response = yield request('/api/add', {
        method: 'post',
        data: {
          employee: employee,
        },
      })
        .then(function (response) {
          if (response != null) {
            alert('提交成功！');
            return response;
          }
        })
        .catch(function (error) {
          console.log(error);
          return null;
        });

      yield put({
        type: 'addEmployee',
        payload: {
          employee: response,
        },
      });
    },

    *updateList({ employee }, { put }) {
      yield request('/api/update', {
        method: 'post',
        data: {
          employee: employee,
        },
      })
        .then(function (response) {
          if (response == 'ok') {
            alert('修改成功！');
          }
        })
        .catch(function (error) {
          console.log(error);
        });
      // yield put({
      //   type: 'updateEmployee',
      //   payload: {
      //     employee: employee,
      //   },
      // });
    },
    *delList({ key }, { call, put }) {
      const response = yield call(request.get, '/api/delList/' + key);
      yield put({
        type: 'delete',
        payload: {
          key: key,
        },
      });
    },
    *getAll(_, { call, put }) {
      const response = yield call(request.get, '/api/lists');

      yield put({
        type: 'update',
        payload: {
          employeeList: response,
        },
      });
    },
  },
};
